<template>
  <div class="contain">
    <div class="daySelect">
      <div class="top">
        <el-date-picker
          v-model="daySelect"
          type="daterange"
          range-separator="-"
          start-placeholder="Start date"
          end-placeholder="End date"
          format="YYYY/MM/DD"
          value-format="YYYY-MM-DD"
          :disabled-date="disableFutureDates"
        />
        <el-select
          v-model="chartDayType"
          placeholder="请选择图表类型"
          style="width: 200px; margin-left: 20px"
          @change="renderChart"
        >
          <el-option label="柱状图" value="bar"></el-option>
          <el-option label="饼图" value="pie"></el-option>
        </el-select>
      </div>
      <div class="dayCharts" ref="dayCharts"></div>
    </div>
    <div class="monthSelect">
      <div class="top">
        <el-date-picker
          v-model="monthSelect"
          type="monthrange"
          range-separator="To"
          start-placeholder="Start month"
          end-placeholder="End month"
          :disabled-date="disableFutureMonths"
        />
        <el-select
          v-model="chartMonthType"
          placeholder="请选择图表类型"
          style="width: 200px; margin-left: 20px"
          @change="renderMonthCharts"
        >
          <el-option label="柱状图" value="bar"></el-option>
          <el-option label="饼图" value="pie"></el-option>
        </el-select>
      </div>
      <div class="monthCharts" ref="monthCharts"></div>
    </div>
    <div class="retentionSelect">
      <div class="top">
        <el-date-picker
          v-model="retentionDate"
          type="date"
          format="YYYY/MM/DD"
          value-format="YYYY-MM-DD"
          placeholder="选择日期"
        />
        <el-select
          v-model="selectedDaysAfter"
          style="width: 200px; margin-left: 20px"
          multiple
          placeholder="选择留存天数"
        >
          <el-option label="1 天" value="1"></el-option>
          <el-option label="3 天" value="3"></el-option>
          <el-option label="7 天" value="7"></el-option>
          <el-option label="30 天" value="30"></el-option>
        </el-select>
      </div>
      <div class="retentionCharts" ref="retentionCharts"></div>
    </div>
  </div>
</template>

<script setup>
import * as echarts from 'echarts'
import dayjs from 'dayjs'
import { onMounted, ref, watch } from 'vue'
import { getDay, getMonth, getRetention } from '@/api/statistics'
import { ElMessage } from 'element-plus'
const daySelect = ref([
  dayjs().format('YYYY-MM-DD'), // 默认选中当天
  dayjs().format('YYYY-MM-DD'),
])
const monthSelect = ref([
  dayjs().format('YYYY-MM'), // 默认选中当月
  dayjs().format('YYYY-MM'),
])

const retentionDate = ref(dayjs().subtract(1, 'day').format('YYYY-MM-DD'))

const selectedDaysAfter = ref(['1'])
const dayCharts = ref(null)
const monthCharts = ref(null)
const retentionCharts = ref(null)
const dayData = ref([])
const monthData = ref([])
const retentionData = ref([])
const chartDayType = ref('bar')
const chartMonthType = ref('bar')
watch(daySelect, () => {
  if (daySelect.value.length === 2) {
    const startDate = dayjs(daySelect.value[0])
    const endDate = dayjs(daySelect.value[1])
    const diffDays = endDate.diff(startDate, 'day')
    if (diffDays > 7) {
      ElMessage.warning('时间范围不能超过 7 天，请重新选择！')
      dayData.value = []
      daySelect.value = []
      return
    }
  }
  getDayData()
})

watch(chartDayType, () => {
  renderDayCharts()
})
watch(chartMonthType, () => {
  renderMonthCharts()
})

watch(monthSelect, () => {
  if (monthSelect.value.length === 2) {
    const startMonth = dayjs(monthSelect.value[0])
    const endMonth = dayjs(monthSelect.value[1])
    const diffMonths = endMonth.diff(startMonth, 'month') // 计算月份间隔

    if (diffMonths > 5) {
      // 只允许选择 6 个月以内（包含起始月）
      ElMessage.warning('月份范围不能超过 6 个月，请重新选择！')
      monthSelect.value = [] // 清空选择
    }
  }
  if (monthSelect.value.length === 2) {
    getMonthData()
    renderMonthCharts()
  }
})

onMounted(() => {
  getDayData()
  getMonthData()
  getRetentionData()
})
watch(retentionDate, () => {
  getRetentionData()
})
watch(selectedDaysAfter, () => {
  getRetentionData()
})

const disableFutureDates = (date) => {
  return date.getTime() > new Date().getTime() // 禁止选择今天之后的日期
}
const disableFutureMonths = (date) => {
  return dayjs(date).isAfter(dayjs(), 'month')
}
const renderDayCharts = () => {
  if (!dayData.value.length > 0) return
  const dates = dayData.value.map((item) => item.date)
  const values = dayData.value.map((item) => item.dau)

  const option =
    chartDayType.value === 'bar'
      ? {
          title: {
            text: '用户日活跃度',
            left: 'center',
          },
          tooltip: {
            trigger: 'axis',
          },
          xAxis: {
            type: 'category',
            data: dates,
          },
          yAxis: {
            type: 'value',
          },
          series: [
            {
              name: '日活跃数',
              type: 'bar',
              data: values,
              barWidth: 60, // 设置柱子的固定宽度（可以调整）
            },
          ],
        }
      : {
          title: {
            text: '用户日活跃度',
            left: 'center',
          },
          tooltip: {
            trigger: 'item',
          },
          series: [
            {
              name: '日活跃数',
              type: 'pie',
              radius: '50%',
              data: dayData.value.map((item) => ({
                value: item.dau,
                name: item.date,
              })),
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(0, 0, 0, 0.5)',
                },
              },
            },
          ],
        }

  const chart = echarts.init(dayCharts.value)
  chart.setOption(option, true)
  window.addEventListener('resize', () => {
    chart.resize()
  })
}
const renderMonthCharts = () => {
  if (!dayData.value.length > 0) return
  const months = monthData.value.map((item) => item.month)
  const values = monthData.value.map((item) => item.mau)
  const option =
    chartMonthType.value === 'bar'
      ? {
          title: {
            text: '用户月活跃度',
            left: 'center',
          },
          tooltip: {
            trigger: 'axis',
          },
          xAxis: {
            type: 'category',
            data: months,
          },
          yAxis: {
            type: 'value',
          },
          series: [
            {
              name: '月活跃数',
              type: 'bar',
              data: values,
              barWidth: 60, // 设置柱子的固定宽度（可以调整）
            },
          ],
        }
      : {
          title: {
            text: '用户月活跃度',
            left: 'center',
          },
          tooltip: {
            trigger: 'item',
          },
          series: [
            {
              name: '月活跃数',
              type: 'pie',
              radius: '50%',
              data: monthData.value.map((item) => ({
                value: item.mau,
                name: item.month,
              })),
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                },
              },
            },
          ],
        }

  const chart = echarts.init(monthCharts.value)
  chart.setOption(option, true)
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

const renderRetentionCharts = () => {
  const days = retentionData.value.retentionRates.map((item) => `${item.days}天`)
  const values = retentionData.value.retentionRates.map((item) => item.retentionRate)
  const date = retentionData.value.date
  console.log('Rendering retention chart with data:', days, values)
  const option = {
    title: {
      text: `${date} 用户留存率`,
      left: 'center',
    },
    tooltip: {
      trigger: 'axis', // 鼠标悬浮时显示工具提示
    },
    xAxis: {
      type: 'category', // 横坐标为分类数据
      data: days, // 映射为 '1天', '3天'
    },
    yAxis: {
      type: 'value', // 纵坐标为数值
      axisLabel: {
        formatter: '{value}%', // 格式化显示百分比
      },
    },
    series: [
      {
        name: '留存率',
        type: 'bar', // 使用柱状图
        data: values, // 提取留存率数据
        barWidth: 60, // 设置柱子的固定宽度（可以调整）
        label: {
          show: true, // 显示标签
          position: 'top', // 标签位置
          formatter: '{c}%', // 在柱子上显示百分数
        },
      },
    ],
  }

  const chart = echarts.init(retentionCharts.value)
  chart.setOption(option, true)
  window.addEventListener('resize', () => {
    chart.resize()
  })
}
const getDayData = async () => {
  const res = await getDay({
    startDate: daySelect.value[0],
    endDate: daySelect.value[1],
  })
  if (res.status === 200 || res.status === 201) {
    dayData.value = res.data.data
    renderDayCharts()
  } else {
    ElMessage.error(res.data.data)
  }
}
const getMonthData = async () => {
  const res = await getMonth({
    startMonth: monthSelect.value[0],
    endMonth: monthSelect.value[1],
  })
  if (res.status === 200 || res.status === 201) {
    monthData.value = res.data.data
    renderMonthCharts()
  } else {
    ElMessage.error(res.data.data)
  }
}

const getRetentionData = async () => {
  const res = await getRetention({
    date: retentionDate.value,
    daysAfter: selectedDaysAfter.value.join(','),
  })
  if (res.status === 200 || res.status === 201) {
    retentionData.value = res.data.data
    console.log(res.data.data)
    console.log('11111')
    renderRetentionCharts()
  } else {
    ElMessage.error(res.data.data)
  }
}
</script>


<style lang='scss' scoped>
.contain {
  padding: 30px;
  .dayCharts {
    margin-top: 20px;
    width: 1000px;
    height: 400px;
  }
  .monthCharts {
    margin-top: 20px;
    width: 1000px;
    height: 400px;
  }
  .retentionCharts {
    margin-top: 20px;
    width: 1000px;
    height: 400px;
  }
}
</style>
